import {
	checkLogin,
	toLogin,
	prePage
} from "@/common/libs/login.js";
import {
	PAGE_BACK_URL_KEY,
	LOGIN_PAGE,
	UPLOAD_FILE_NUM,
} from "@/config/global.js";
import Cache from "@/utils/cache.js";
import {
	mutiUploadFile
} from "@/utils/file.js";

/**
 * @param {String} 路径，
 * @param {Object} 参数，
 * @param {Function} 成功的回调 
 * @param {String} 跳转类型 
 * @param {Number} 返回几页： 负数表示上几页页，大于-1表示具体的页面    
 */
export const go = function(path, query, type = "navigateTo", other = {
	backIndex: 1,
	// 判断是否需要登录才能跳转
	noAuth: true
}) {
	let queryStr = "";
	if(query) {
		//遍历query对象
		const keys = Object.keys(query);
		// 当query存在参数时对其属性进行遍历
		keys.forEach((key, index) => {
			if(0 == index) queryStr += "?";
			// 数组参数要转换
			if(Array.isArray(query[key])) {
				queryStr += `${key}=${encodeURIComponent(JSON.stringify(query[key]))}`;
			} else queryStr += `${key}=${query[key]}`;
			
			if(keys.length - 1 != index) queryStr += "&";
		});
	}
	
	const {successFn, noAuth} = other;
	const goPage = path + queryStr;
	// 跳转的页面是否需要登录才能进入
	if(!noAuth && !checkLogin()) {
		console.error("用户未登录")
		Cache.set(PAGE_BACK_URL_KEY, goPage);
		// #ifdef APP-PLUS
		// go(LOGIN_PAGE,{});
		return skipPage(LOGIN_PAGE, type)
		// #endif
		// #ifdef H5
		return skipPage(LOGIN_PAGE, 'reLaunch');
		// #endif
		// #ifdef MP-WEIXIN
		return skipPage(LOGIN_PAGE, type);
		// #endif
	}
	
	return skipPage(goPage, type, other);
}

function skipPage(goPage, type, other = {
	backIndex: 1
}) {
	const {successFn, backIndex} = other;
	
	const router = {
		navigateTo: uni.navigateTo,
		redirect: uni.redirectTo,
		reLaunch: uni.reLaunch,
		switchTab: uni.switchTab
	}
	
	return new Promise((resolve, reject) => {
		// 当所有跳转方式都匹配不上时，报错
		if(
			["navigateTo", "redirect", "reLaunch", "switchTab", "navigateBack"].indexOf(type) == -1
		) {
			console.error(`type:${type}类型错误，type可选值为：`+ "navigateTo，"+"redirect，"+"reLaunch，"+"switchTab"+"，navigateBack");
			return reject();
		}
		
		
		
		// 因为参数都一样，所有直接定义在一个对象中
		let commonObj = {
			success: () => {
				successFn && successFn();	
				return resolve();
			},
			fail: (err) => {
				console.error(err);
				return reject(err);
			}
		}
		// 当跳转方式为返回时有两种情况
		if(type === "navigateBack") {
			const backPage = prePage(true);
			const {backIndex} = other;		
			// 跳转具体的页面
			if(backIndex > 1) {
				uni.navigateBack({
					url: goPage,
					...commonObj
				})
			}
			// 跳转非具体页面
			else if(backIndex == 1 && backPage == LOGIN_PAGE){
				uni.reLaunch({
					url: "/pages/index/index",
					...commonObj
				})
			}else {
				uni.navigateBack({
					delta: backIndex,
					...commonObj
				})
			}
		}else {
			router[type]({
				url: goPage,
				...commonObj
			})
		}
	});
}

/**
 * @param {String}
 * @param {Function}
 * @param {Function}
 * @param {Function}
 * @param {Object}
 * @return {Promise}
 */
export const message = function(title, success, fail, complete, other = {
	icon: "none"
}){
	return new Promise((resolve, reject) => {
		const { icon, image, mask, duration, position} = other;
		uni.showToast({
			title: title? title : '',
			icon: icon? icon : 'none',
			image: image? image : '' ,
			mask: mask? mask : false,
			duration: duration? duration : 1500,
			position: position? position : 'center',
			success() {
				success && success();
				return resolve();
			},
			fail() {
				fail && fail();
				return reject();
			},
			complete() {
				complete && complete();
			}
		})
	})
}

/**
 * 封装选择图片
 */
export const chooseImage = function(attrs = {
	sizeType: ['original', 'compressed'],
	sourceType: ['album'],
	count: UPLOAD_FILE_NUM
}) {
	return new Promise((resolve, reject) => {
		const {sizeType, sourceType, count} = attrs;
		uni.chooseImage({
			count, //默认9
			sizeType: sizeType, //可以指定是原图还是压缩图，默认二者都有
			sourceType: sourceType, //从相册选择
			success: (res) => {
				let files = res.tempFiles;
				const backData = mutiUploadFile(files);
				return resolve(backData);
			},
			fail: (err) => reject(err)
		})
	})
}

/**
 * 时间格式化
 * @param {String}
 */
export const dateFormat = function(date = new Date().getTime()) {
	date = new Date(date);
	let year = date.getFullYear();                // 年
	let month = showTime(date.getMonth() + 1);        // 月
	let day = showTime(date.getDate());          // 日
	let hours = showTime(date.getHours());         // 小时
	let minutes = showTime(date.getMinutes());    // 分钟
	let second = showTime(date.getSeconds());     // 秒
	let str = '';
	str = str + year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + second
	return str
}

function showTime(t) {
	let time
	time = t > 10 ? t : '0' + t
	return time
}
